import {Component, OnInit} from '@angular/core';
import {ApiService} from '@core/services/http/api.service';
import { HeaderDayComponent } from "@shared/ag-grid-ext/header-component/header-day.component";
import {dateFormat, deepClone} from '../../../utils/utils';
import {ApesMessageService} from "@shared/apes/message";
import {GridConfigService} from "@core/config/grid-config.service";
import {GridOptions} from '@ag-grid-community/core';
import {endOfMonth, format, startOfMonth} from "date-fns";
import {HttpClient} from "@angular/common/http";
import {AllModules,Module} from "@ag-grid-enterprise/all-modules";

@Component({
  selector: 'schedule',
  templateUrl: './schedule-form.component.html',
  styleUrls: ['./schedule-form.component.scss'],
})
export class ScheduleFormComponent implements OnInit {
  /** grid 相关 **/
  modules:Module[] =AllModules;
  rowData: any[] = [];
  rowDataItem: any[] = [];
  columnDefsMeteData: any[];
  columnDefsItemMeteData: any[];
  columnDefs: any = [];
  gridOptions: GridOptions;
  height: any = 520 + 'px';
  tabList:any=[];
  ctx = {model: {}};
  localeText: any;
  headDate:any;
  /** 按钮相关 **/
  buttonBar = [
    // {hide: true, style: 'default', label: '导出', id: 'action_export'},
    {hide: true, style: 'primary', label: '查询', id: 'action_query', loading: false},
    { hide: true, style: 'default', label: '同步', id: 'action_syn' },
    // { hide: true, style: 'default', label: '重置', id: 'action_reset' },
    // { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
  ];

  /** 明细数据查询条件 **/
  hind: string = 'none';     // 中间必填项
  timeList: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  endDate = null;                     // 默认结束时间
  startDate = null;                   // 默认开始时间 当天
  itemsList = {};
  tabsId: string;

  /** 分页器 **/
  total = 0;
  pageSize = 50;
  currentPage = 0;

  /** 获取公司、部门、合作伙伴相关 **/
  hidn: string = 'none';            // 脑袋必填项
  company:any[];
  companyId: string = null;
  dept = [];
  deptId: string = null;
  employee = [];
  employeeId: string = null;
  postId: string = null;
  frameworkComponents;



  constructor(private apiService: ApiService,
              private msg: ApesMessageService,
              private http:HttpClient,
              private gridConfigService: GridConfigService) {
    this.columnDefsMeteData = [
      {
        headerName: "公司代码",
        field: "COMPANY_ID",
        width: 100,
        hide:true
      },
      {
        headerName: "公司名称",
        field: "COMPANY_NAME",
        width: 235,
        pinned:"left"
      },
      {
        headerName: "部门代码",
        field: "DEPT_ID",
        width: 100,
        hide:true
      },
      {
        headerName: "部门名称",
        field: "DEPT_NAME",
        width: 100,
        pinned:"left"
      },
      {
        headerName: "岗位代码",
        field: "POST_ID",
        width: 100,
        hide:true
      },
      {
        headerName: "岗位名称",
        field: "POST_NAME",
        width: 100,
        pinned:"left"
      },
      {
        headerName: "员工代码",
        field: "EMPLOYEE_ID",
        width: 100,
        hide:true
      },
      {
        headerName: "法定节假日",
        field: "HOLIDAYS",
        width: 100,
        pinned:"right"
      },
      {
        headerName: "员工名称",
        field: "EMPLOYEE_NAME",
        width: 100,
        pinned:"left"
      }
    ];
    this.localeText = gridConfigService.getLocaleText();
  }

  ngOnInit() {

    // 默认 请求 当天 数据
    const today = new Date();
    const startMonth = startOfMonth(today); //Tue Jan 01 2019 00:00:00 GMT+0800 (中国标准时间)
    const startDate = format(startMonth, 'YYYY-MM-DD'); // 2019-01-01 00:
    const endMonth = endOfMonth(today); //Thu Jan 31 2019 23:59:59 GMT+0800 (中国标准时间)
    const endDate = format(endMonth, 'YYYY-MM-DD'); // 2019-01-31 23:59:59
    this.endDate = endDate;
    this.startDate = startDate
    this.timeList.push(this.startDate);
    this.timeList.push(this.endDate);

    this.frameworkComponents = { headerDay: HeaderDayComponent };
    // this.getCompany();
    // this.getDept();
    // this.getEmployee();
    this.onHead();
    // this.getPartner();
  }

  onRowClick() {

  }

  onHead(){
    this.apiService.post('ding.schedule.getScheduleHead', {'TIME_LIST':this.timeList}).subscribe(data => {
      let iLength = data.length;
      this.headDate = data;
      this.columnDefs = deepClone(this.columnDefsMeteData);
      for (let i = 0; i < iLength; i++) {
        this.dynamicField(data[i]);
      }
      this.columnDefs.push( {
        headerName: "例休计划",
        field: "REST",
        width: 100,
        pinned:"right",
        valueGetter: function(params) {
          let iCount = 0;
          let columnList = params.columnApi.columnController.columnDefs
          let iSize = columnList.length-2;
          for (let i = 8 ;i< iSize ; i++){
            if (params.data[columnList[i].field]==null)
              iCount +=1;
           }
          return iCount;
        }
      });
      this.columnDefs.push( {
        headerName: "应出勤",
        field: "ATTENDANCE",
        width: 100,
        pinned:"right",
        valueGetter: function(params) {
          let iCount = 0;
          let columnList = params.columnApi.columnController.columnDefs
          let iSize = columnList.length-2;
          for (let i = 9 ;i< iSize ; i++){
            if (params.data[columnList[i].field]!=undefined)
              iCount +=1;
          }
          return iCount;
        }
      });

    });
  }


  onPageIndexChange() {
    this.getTableTabData(this.itemsList);
  }

  dynamicField(item: any) {
    // var name = item.name;
    // var strs = name.split(";"); //字符分割
    let field = {
      headerName: item.name,
      field: item.id,
      width: 50,
      cellRenderer: this.formatDate,
      cellClass: function(params) {
        return params.value === 0 ? "rubinered" : "";
      },
      headerComponent:"headerDay"
    }
    this.columnDefs.push(field);
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.action_query();
      } else if (data.id === 'action_syn') {
        this.action_syn();
      }
      // else if (data.id === 'action_export') {
      //   this.action_export();
      // }
      // else if (data.id === 'action_show') {
      //   this.action_show();
      // } else if (data.id === 'action_reset') {
      //         this.action_reset();
      //       }
    }
  }

  /** 主数据 查询按钮事件 **/
  action_query() {
    if(this.timeList.length === 0 && this.companyId === null && this.deptId === null && this.employeeId === null && this.postId === null){
      this.hidn = 'block';
    }else {
      this.hidn = 'none';
      this.getTableFieldData();
    }
    this.buttonBar[0].loading = false;
  }
  /** 同步数据 同步按钮事件 **/
  action_syn(){
    if(this.timeList.length === 0 && this.companyId === null && this.deptId === null && this.employeeId === null && this.postId === null){
      this.hidn = 'block';
    }else {
      this.hidn = 'none';
      let data = {'COMPANY_ID': this.companyId,'POST_ID':this.postId, 'DEPT_ID': this.deptId, 'EMPLOYEE_ID': this.employeeId,'TIME_LIST':this.timeList};
      this.apiService.post('ding.schedule.synSchedule', {'body': JSON.stringify(data)}).subscribe(data => {
        if (data) {
          this.rowData = data;
          if (this.rowData.length === 0) {
            this.msg.info(`未找到满足条件的数据`);
          }
        } else {
          this.rowData = [];
          this.msg.info('未找到满足条件的数据');
        }
      })
    }
    this.buttonBar[0].loading = false;
  }

  /** 明细数据 查询按钮事件 **/
  queryBtn() {
    this.getDate(this.timeList, 'startValue', 'endValue');
    // 判断日期不能为空
    if (this.startValue === null) {
      this.hind = 'block';
    } else {
      this.hind = 'none';
    }
    //  必须满足以下条件才能调用接口
    if (this.hind === 'none') {
      this.getTableTabData(this.itemsList);
    }
  }

  /** 点击tab页签触发的事件 **/
  tabChanges(tabId: any) {
    this.currentPage = 0;
    this.tabsId = tabId;
    this.getTableTabData(this.itemsList);
  }


  /** 日期转换 **/
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  /** 主表数据 **/
  getTableFieldData() {
    this.onHead();
    let data = {'COMPANY_ID': this.companyId,'POST_ID':this.postId, 'DEPT_ID': this.deptId, 'EMPLOYEE_ID': this.employeeId,'TIME_LIST':this.timeList};
    this.apiService.post('ding.schedule.loopSchedule', {'body': JSON.stringify(data)}).subscribe(data => {
      if (data) {
        this.rowData = data;
        if (this.rowData.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.rowData = [];
        this.msg.info('未找到满足条件的数据');
      }
    })

  }



  /** 明细数据 **/
  getTableTabData( list: any ) {
    // this.rowDataItem = [];
    let data = {
      'queryid':'ledger.items','page': this.currentPage,'size': this.pageSize,
      'LEDGER_ACCOUNT_ID': this.tabsId,
      'ACCOUNTING_DATE_BEGIN': this.startValue, 'ACCOUNTING_DATE_END': this.endValue,
      'COMPANY_ID': list.COMPANY_ID, 'DEPT_ID': list.DEPT_ID, 'PARTNER_ID': list.PARTNER_ID,
      'INVENTORY_MODE': list.INVENTORY_MODE, 'ACCOUNTING_METHOD': list.ACCOUNTING_METHOD
    };
    this.apiService.post('pub.query', {'body': JSON.stringify(data)}).subscribe(data => {
      if (data) {
        this.total = data.total;
        this.rowDataItem = data.content;
        if (this.rowDataItem.length === 0) {
          this.msg.info(`未找到满足条件的数据`);
        }
      } else {
        this.msg.info(data.msg);
      }
    })
  }

  /** 获取 公司 **/
  getCompany() {
    let data = {'pages': 1, 'size': 5000 };
    this.apiService.post('cm.company.find', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.company = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 获取 部门 **/
  getDept() {
    let data = { 'size': 10000, page: 0 };
    this.apiService.post('cm.branch.findAll', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.dept = body;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 获取 员工 **/
  getEmployee() {

    this.apiService.post('hr.employee.findAll', {}).subscribe(
      (body) => {
        if (body) {
          this.employee = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  /** 保留两位小数点 **/
  formatDate(params) {
    let key = params.colDef.field;
    let data =params.data[key];
    if ( data !== undefined ) {
      data = 'A';
    } else{
      data = '休';
    }
    return data;
  }
}

